package com.win;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fyl.exception.UnifiedExceptionHandler;
import com.fyl.schedule.EnableQuartz;
import com.fyl.schedule.JobDefinition;
import com.fyl.schedule.QuartzManager;
import com.fyl.security.anno.EnableOAuth;
import com.fyl.validation.anno.EnableValidation;
import com.win.oauth.entity.Task;
import com.win.oauth.utils.ElasticSearchUtils;
import com.win.oauth.service.ITaskService;
import com.win.oauth.service.impl.OAuthServiceImpl;
import org.elasticsearch.common.Strings;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.quartz.QuartzProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

@SpringBootApplication(/*exclude = {DruidDataSourceAutoConfigure.class}*/)
//@EnableAsyncLog(LogServiceImpl.class)
@Import({UnifiedExceptionHandler.class})
@EnableQuartz
@EnableValidation
@EnableOAuth(OAuthServiceImpl.class)
public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    @Autowired
    QuartzManager quartzManager;

    @Autowired
    ITaskService taskService;

    @Autowired
    QuartzProperties quartzProperties;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }


    @Bean
    public ApplicationRunner buildApplicationRunner() {
        return (args) -> {
            logger.info("server is started! ");
            List<Map<String, Object>> test = selectPage("test");
            System.err.println(test);
            if (quartzProperties.isAutoStartup()) {
                List<Task> tasks = taskService.lambdaQuery().eq(Task::getDbStatus, 1).list();
                List<JobDefinition> list = tasks.stream().map(task -> taskService.buildJob(task)).collect(toList());
                quartzManager.startup(list);
            }
        };
    }

    @Autowired
    ElasticSearchUtils elasticSearchUtils;

    public List<Map<String, Object>> selectPage(String index) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", "2");
        map.put("name", "王wu");
        map.put("text", "i'm 王五");
        elasticSearchUtils.submitData(map, index, map.get("id").toString());
        //构建查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //精确查询
        //boolQueryBuilder.must(QueryBuilders.wildcardQuery("name", "张三"));
        // 模糊查询
//        boolQueryBuilder.filter(QueryBuilders.wildcardQuery("name", "李*"));
        // 范围查询 from:相当于闭区间; gt:相当于开区间(>) gte:相当于闭区间 (>=) lt:开区间(<) lte:闭区间 (<=)
//        boolQueryBuilder.filter(QueryBuilders.rangeQuery("age").from(18).to(32));
        SearchSourceBuilder query = new SearchSourceBuilder();
        query.query(boolQueryBuilder);
        //需要查询的字段，缺省则查询全部
        String fields = "";
        //需要高亮显示的字段
        String highlightField = "name";
        if (StringUtils.isNotBlank(fields)) {
            //只查询特定字段。如果需要查询所有字段则不设置该项。
            query.fetchSource(new FetchSourceContext(true, fields.split(","), Strings.EMPTY_ARRAY));
        }
        //分页参数，相当于pageNum
        Integer from = 0;
        //分页参数，相当于pageSize
        Integer size = 2;
        //设置分页参数
        query.from(from);
        query.size(size);

        //设置排序字段和排序方式，注意：字段是text类型需要拼接.keyword
        //query.sort("age", SortOrder.DESC);
//        query.sort("name" + ".keyword", SortOrder.ASC);
        List<Map<String, Object>> maps = elasticSearchUtils.searchListData(index, query, highlightField);
        return maps;
    }


}
